<script setup>
// import { nextTick } from 'vue'
import { Chart } from '@antv/g2'
import dayjs from 'dayjs'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  ready: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['queryChange'])

let chartInstance = null
const chartDomRef = ref(null)

const state = reactive({
  isInited: false,
  years: [],
  months: [],
  query: {
    year: `${dayjs().year()}`,
    // month: dayjs().month() + 1,
    month: '',
  },
  mounted: false,
  mountCheckCount: 0,
})

const isNoData = computed(() => state.isInited && !props.data.length)

// 初始化渲染图表
const createChartView = (container, { width, height }) => {
  const chart = new Chart({
    container,
    autoFit: true,
    // height: height || 196,
    // width: width || 600,
    marginLeft: -2,
    marginRight: 12,
    marginTop: 0,
  })

  const chartData = props.data.destructionList || []
  // 找出chartData中totalNum的最大值
  const maxTotalNum = Math.max(...chartData.map(item => item.totalNum))

  // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '图表数据', width, chartData)

  chart
    .data(chartData)
    .scale('x', {
      range: [0, 1],
    })
    .scale('y', {
      nice: true,
      domain: [0, maxTotalNum + 10],
    })
    .axis('x', {
      title: false,
      line: true,
      lineFill: '#E6F6FF',
      lineStroke: '#E6F6FF',
      lineLineWidth: 1,
      lineLineDash: [0, 0],
    })
    .axis('y', {
      title: false,
      line: false,
      gridStroke: '#E6F6FF',
      gridStrokeOpacity: 0.5,
      position: 'top',
      labelAlign: 'perpendicular',
      // labelFilter: (datum, idx) => idx % 2 === 0,
      // gridFilter: (datum, idx) => idx % 2 === 0,
    })
    .theme({ type: 'custom' })
    // .style({
    //   viewFill: '#4e79a7',
    //   plotFill: '#f28e2c',
    //   mainFill: '#e15759',
    //   contentFill: '#76b7b2',
    // })

  chart.interval()
    .coordinate({ transform: [{ type: 'transpose' }] })
    .encode('x', 'deptName')
    .encode('y', 'totalNum')
    .tooltip({
      items: [{ name: '送销总数', channel: 'y' }],
    })
    .style({
      minWidth: 6,
      maxWidth: 12,
    })
    .style('fill', () => {
      return 'linear-gradient(180deg,rgba(21,177,255,0.00) 0%, #15b1ff)'
    })

  chart.point()
    .encode('x', 'deptName')
    .encode('y', 'totalNum')
    .encode('shape', 'line')
    .encode('size', 5)
    .style({
      fill: '#15b1ff',
      stroke: '#15b1ff',
      lineWidth: 3,
    })
  chart.render()

  state.isInited = true

  return chart
}

// 更新图表数据
const updateChartView = (chart) => {
  // 获得 Interval Mark
  // const interval = chart.getNodesByType('interval')[0]

  // // 模拟并且更新 Interval 的数据
  // const newData = interval.data().map(d => ({
  //   ...d,
  //   sold: Math.random() * 400 + 100,
  // }))

  // interval.data(newData)

  chart.changeData(props.data.destructionList)
  // 重新渲染
  chart.render()
}

watch([() => props.data, () => props.ready, () => state.mountCheckCount], ([newData, newReady]) => {
  if(state.isInited && chartInstance) {
    // 已经初始化过图表, 直接更新数据
    // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '更新图表数据', newData)
    updateChartView(chartInstance)
  }
  else {
    // 查看数据接口是否已经准备好
    if(props.ready || newReady) {
      if(!state.mounted) {
        setTimeout(() => {
          state.mountCheckCount++
        }, 20)
        return
      }
      // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '初始化图表1', state.mounted, newData, chartDomRef.value)
      if(newData?.destructionList?.length && chartDomRef.value) {
        // 请求数据成功, 初始化图表
        const { width, height } = chartDomRef.value.getBoundingClientRect()
        chartInstance = createChartView(chartDomRef.value, { width, height })
        // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '初始化图表2', newData)
        emit('queryChange', state.query)
      }
      else {
        // 图标数据为空，更新初始化状态, 展示缺省空状态
        state.isInited = true
        // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '图表数据为空', props.data)
      }
    }
    else {
      // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '等待数据请求完成', newData)
    }
  }
}, { deep: true, immediate: true })

const genMonths = (year) => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1
  const defaultAll = [{
    label: '全部',
    value: '',
  }]
  const months = Array.from({ length: 12 }, (_, i) => {
    const m = i + 1
    return {
      label: `${m}月`,
      value: `${m}`,
    }
  })
  if(year === currentYear) {
    state.months = defaultAll.concat(months.slice(0, currentMonth))
  }
  state.months = defaultAll.concat(months)
  state.query.month = ''
}

const changeYear = (year) => {
  genMonths(year)
  emit('queryChange', state.query)
}

const changeMonth = () => {
  emit('queryChange', state.query)
}

onMounted(() => {
  // 初始化年份和月份
  state.mounted = true
  const year = dayjs().year()

  // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '年份', year)
  state.years = Array.from({ length: 10 }, (_, i) => {
    const y = year - i
    return {
      label: `${y}年`,
      value: `${y}`,
    }
  })
  genMonths(year)
})

const { years, months, query } = toRefs(state)
</script>

<template>
  <section class="dispatch-stats dispatch-stats-chart">
    <UiSubPanel title="送销单位物料统计" stretch size="large">
      <div class="panel-content-wrap">
        <div class="form-wrap">
          <n-form
            inline
            label-width="auto"
            label-placement="left"
            :model="query"
            size="medium"
          >
            <n-form-item label="年份 :">
              <n-select v-model:value="query.year" :options="years" @update:value="changeYear" />
            </n-form-item>
            <n-form-item label="月份 :">
              <n-select v-model:value="query.month" :options="months" @update:value="changeMonth" />
            </n-form-item>
          </n-form>
        </div>
        <div ref="chartDomRef" class="panel-layout panel-layout--chart" />
      </div>
    </UiSubPanel>

    <UiEmpty v-show="isNoData.value" />
  </section>
</template>

<style lang='scss' scoped>
.dispatch-stats {
  &-chart {
    height: 93.5%;
    padding: 20px 30px;
    margin-top: 16px;
    color: #fff;
    background-image: linear-gradient(90deg, #009de333 0%, #009DE329 100%);

    .panel-content-wrap {
      display: flex;
      flex-direction: column;
      height: 100%;
    }

    .form-wrap {
      display: flex;
      align-items: center;
      padding: 20px 0 0;

      :deep(.n-form.n-form--inline) {
        .n-form-item .n-form-item-label {
          color: #80E3FB;
        }

        .n-form-item .n-form-item-blank {
          min-width: 200px;

        }

        .n-select .n-base-selection {
          --n-text-color: #80E3FB !important;
          --n-arrow-color: #80E3FB !important;
          --n-color: transparent !important;
          --n-color-active: transparent !important;

          &--selected {
            --n-border: 1px solid #80E3FB !important;
            --n-border-active: 1px solid #0EF !important;
            --n-border-focus: 1px solid #36ad6a;
            --n-border-hover: 1px solid #0EF !important;
          }
        }

      }
    }
  }
}

.panel-layout {
  &--chart {
    display: flex;
    flex: 1;
    width: 100%;
    min-height: 0;

    :deep(canvas) {
      flex: 1;
    }
  }
}
</style>
